3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
257 $this->mOutput
->setText( $text );
258 wfProfileOut( $fname );
260 return $this->mOutput
;
264 * Get a random string
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
302 if( $tag == STRIP_COMMENTS
) {
303 $start = '/<!--()()/';
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
313 if( count( $p ) < 4 ) {
320 $marker = $rnd . sprintf('%08X', $n++
);
321 $stripped .= $marker;
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
356 return Parser
::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType
== OT_HTML
);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
382 $ext_params = array();
383 $gallery_content = array();
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix
;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
392 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
398 $html_content[$marker] = '<html>'.$content.'</html>';
404 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
414 if( $this->mOptions
->getUseTeX() ) {
415 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
418 $math_content[$marker] = renderMath( $content );
420 $math_content[$marker] = '<math>'.$content.'</math>';
426 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
436 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
448 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
455 foreach ( $this->mTagHooks
as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
465 if ( is_null( $content ) ) {
467 $ext_content[$tag][$marker] = $full_tag;
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
475 # Merge state with the pre-existing state, if there is one
477 $state['html'] = $state['html'] +
$html_content;
478 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
479 $state['math'] = $state['math'] +
$math_content;
480 $state['pre'] = $state['pre'] +
$pre_content;
481 $state['comment'] = $state['comment'] +
$comment_content;
482 $state['gallery'] = $state['gallery'] +
$gallery_content;
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] +
$array;
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'comment' => $comment_content,
496 'gallery' => $gallery_content,
503 * restores pre, math, and hiero removed by strip()
505 * always call unstripNoWiki() after this one
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
526 * always call this after unstrip() to preserve the order
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
565 'comment' => array(),
566 'gallery' => array(),
569 $state['item'][$rnd] = $text;
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser
::internalTidy( $wrappedtext );
595 $correctedtext = Parser
::externalTidy( $wrappedtext );
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
601 return $correctedtext;
605 * Spawn an external HTML tidy process and get corrected markup back from it.
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 fwrite($pipes[0], $text);
628 while (!feof($pipes[1])) {
629 $cleansource .= fgets($pipes[1], 1024);
632 proc_close($process);
635 wfProfileOut( $fname );
637 if( $cleansource == '' && $text != '') {
638 // Some kind of error happened, so we couldn't get the corrected text.
639 // Just give up; we'll use the source text and append a warning.
647 * Use the HTML tidy PECL extension to use the tidy library in-process,
648 * saving the overhead of spawning a new process. Currently written to
649 * the PHP 4.3.x version of the extension, may not work on PHP 5.
651 * 'pear install tidy' should be able to compile the extension module.
656 function internalTidy( $text ) {
658 $fname = 'Parser::internalTidy';
659 wfProfileIn( $fname );
661 tidy_load_config( $wgTidyConf );
662 tidy_set_encoding( 'utf8' );
663 tidy_parse_string( $text );
665 if( tidy_get_status() == 2 ) {
666 // 2 is magic number for fatal error
667 // http://www.php.net/manual/en/function.tidy-get-status.php
670 $cleansource = tidy_get_output();
672 wfProfileOut( $fname );
677 * parse the wiki syntax used to render tables
681 function doTableStuff ( $t ) {
682 $fname = 'Parser::doTableStuff';
683 wfProfileIn( $fname );
685 $t = explode ( "\n" , $t ) ;
686 $td = array () ; # Is currently a td tag open?
687 $ltd = array () ; # Was it TD or TH?
688 $tr = array () ; # Is currently a tr tag open?
689 $ltr = array () ; # tr attributes
690 $has_opened_tr = array(); # Did this table open a <tr> element?
691 $indent_level = 0; # indent level of the table
692 foreach ( $t AS $k => $x )
695 $fc = substr ( $x , 0 , 1 ) ;
696 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
697 $indent_level = strlen( $matches[1] );
699 $attributes = $this->unstripForHTML( $matches[2] );
701 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
702 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
703 array_push ( $td , false ) ;
704 array_push ( $ltd , '' ) ;
705 array_push ( $tr , false ) ;
706 array_push ( $ltr , '' ) ;
707 array_push ( $has_opened_tr, false );
709 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
710 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
711 $z = "</table>" . substr ( $x , 2);
712 $l = array_pop ( $ltd ) ;
713 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
714 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
715 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
717 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
719 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
720 $x = substr ( $x , 1 ) ;
721 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
723 $l = array_pop ( $ltd ) ;
724 array_pop ( $has_opened_tr );
725 array_push ( $has_opened_tr , true ) ;
726 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
727 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
730 array_push ( $tr , false ) ;
731 array_push ( $td , false ) ;
732 array_push ( $ltd , '' ) ;
733 $attributes = $this->unstripForHTML( $x );
734 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
736 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
738 if ( '|+' == substr ( $x , 0 , 2 ) ) {
740 $x = substr ( $x , 1 ) ;
742 $after = substr ( $x , 1 ) ;
743 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
744 $after = explode ( '||' , $after ) ;
747 # Loop through each table cell
748 foreach ( $after AS $theline )
753 $tra = array_pop ( $ltr ) ;
754 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
755 array_push ( $tr , true ) ;
756 array_push ( $ltr , '' ) ;
757 array_pop ( $has_opened_tr );
758 array_push ( $has_opened_tr , true ) ;
761 $l = array_pop ( $ltd ) ;
762 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
763 if ( $fc == '|' ) $l = 'td' ;
764 else if ( $fc == '!' ) $l = 'th' ;
765 else if ( $fc == '+' ) $l = 'caption' ;
767 array_push ( $ltd , $l ) ;
770 $y = explode ( '|' , $theline , 2 ) ;
771 # Note that a '|' inside an invalid link should not
772 # be mistaken as delimiting cell parameters
773 if ( strpos( $y[0], '[[' ) !== false ) {
774 $y = array ($theline);
776 if ( count ( $y ) == 1 )
777 $y = "{$z}<{$l}>{$y[0]}" ;
779 $attributes = $this->unstripForHTML( $y[0] );
780 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
783 array_push ( $td , true ) ;
788 # Closing open td, tr && table
789 while ( count ( $td ) > 0 )
791 $l = array_pop ( $ltd ) ;
792 if ( array_pop ( $td ) ) $t[] = '</td>' ;
793 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
794 if ( array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
798 $t = implode ( "\n" , $t ) ;
799 wfProfileOut( $fname );
804 * Helper function for parse() that transforms wiki markup into
805 * HTML. Only called for $mOutputType == OT_HTML.
809 function internalParse( $text ) {
813 $fname = 'Parser::internalParse';
814 wfProfileIn( $fname );
816 # Remove <noinclude> tags and <includeonly> sections
817 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
818 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
819 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
821 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
822 $text = $this->replaceVariables( $text, $args );
824 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
826 $text = $this->doHeadings( $text );
827 if($this->mOptions
->getUseDynamicDates()) {
828 $df =& DateFormatter
::getInstance();
829 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
831 $text = $this->doAllQuotes( $text );
832 $text = $this->replaceInternalLinks( $text );
833 $text = $this->replaceExternalLinks( $text );
835 # replaceInternalLinks may sometimes leave behind
836 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
837 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
839 $text = $this->doMagicLinks( $text );
840 $text = $this->doTableStuff( $text );
841 $text = $this->formatHeadings( $text, $isMain );
843 wfProfileOut( $fname );
848 * Replace special strings like "ISBN xxx" and "RFC xxx" with
849 * magic external links.
853 function &doMagicLinks( &$text ) {
854 $text = $this->magicISBN( $text );
855 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
856 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
861 * Parse headers and return html
865 function doHeadings( $text ) {
866 $fname = 'Parser::doHeadings';
867 wfProfileIn( $fname );
868 for ( $i = 6; $i >= 1; --$i ) {
869 $h = str_repeat( '=', $i );
870 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
871 "<h{$i}>\\1</h{$i}>\\2", $text );
873 wfProfileOut( $fname );
878 * Replace single quotes with HTML markup
880 * @return string the altered text
882 function doAllQuotes( $text ) {
883 $fname = 'Parser::doAllQuotes';
884 wfProfileIn( $fname );
886 $lines = explode( "\n", $text );
887 foreach ( $lines as $line ) {
888 $outtext .= $this->doQuotes ( $line ) . "\n";
890 $outtext = substr($outtext, 0,-1);
891 wfProfileOut( $fname );
896 * Helper function for doAllQuotes()
899 function doQuotes( $text ) {
900 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
901 if ( count( $arr ) == 1 )
905 # First, do some preliminary work. This may shift some apostrophes from
906 # being mark-up to being text. It also counts the number of occurrences
907 # of bold and italics mark-ups.
911 foreach ( $arr as $r )
913 if ( ( $i %
2 ) == 1 )
915 # If there are ever four apostrophes, assume the first is supposed to
916 # be text, and the remaining three constitute mark-up for bold text.
917 if ( strlen( $arr[$i] ) == 4 )
922 # If there are more than 5 apostrophes in a row, assume they're all
923 # text except for the last 5.
924 else if ( strlen( $arr[$i] ) > 5 )
926 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
929 # Count the number of occurrences of bold and italics mark-ups.
930 # We are not counting sequences of five apostrophes.
931 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
932 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
933 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
938 # If there is an odd number of both bold and italics, it is likely
939 # that one of the bold ones was meant to be an apostrophe followed
940 # by italics. Which one we cannot know for certain, but it is more
941 # likely to be one that has a single-letter word before it.
942 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
945 $firstsingleletterword = -1;
946 $firstmultiletterword = -1;
948 foreach ( $arr as $r )
950 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
952 $x1 = substr ($arr[$i-1], -1);
953 $x2 = substr ($arr[$i-1], -2, 1);
955 if ($firstspace == -1) $firstspace = $i;
956 } else if ($x2 == ' ') {
957 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
959 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
965 # If there is a single-letter word, use it!
966 if ($firstsingleletterword > -1)
968 $arr [ $firstsingleletterword ] = "''";
969 $arr [ $firstsingleletterword-1 ] .= "'";
971 # If not, but there's a multi-letter word, use that one.
972 else if ($firstmultiletterword > -1)
974 $arr [ $firstmultiletterword ] = "''";
975 $arr [ $firstmultiletterword-1 ] .= "'";
977 # ... otherwise use the first one that has neither.
978 # (notice that it is possible for all three to be -1 if, for example,
979 # there is only one pentuple-apostrophe in the line)
980 else if ($firstspace > -1)
982 $arr [ $firstspace ] = "''";
983 $arr [ $firstspace-1 ] .= "'";
987 # Now let's actually convert our apostrophic mush to HTML!
996 if ($state == 'both')
1003 if (strlen ($r) == 2)
1006 { $output .= '</i>'; $state = ''; }
1007 else if ($state == 'bi')
1008 { $output .= '</i>'; $state = 'b'; }
1009 else if ($state == 'ib')
1010 { $output .= '</b></i><b>'; $state = 'b'; }
1011 else if ($state == 'both')
1012 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1013 else # $state can be 'b' or ''
1014 { $output .= '<i>'; $state .= 'i'; }
1016 else if (strlen ($r) == 3)
1019 { $output .= '</b>'; $state = ''; }
1020 else if ($state == 'bi')
1021 { $output .= '</i></b><i>'; $state = 'i'; }
1022 else if ($state == 'ib')
1023 { $output .= '</b>'; $state = 'i'; }
1024 else if ($state == 'both')
1025 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1026 else # $state can be 'i' or ''
1027 { $output .= '<b>'; $state .= 'b'; }
1029 else if (strlen ($r) == 5)
1032 { $output .= '</b><i>'; $state = 'i'; }
1033 else if ($state == 'i')
1034 { $output .= '</i><b>'; $state = 'b'; }
1035 else if ($state == 'bi')
1036 { $output .= '</i></b>'; $state = ''; }
1037 else if ($state == 'ib')
1038 { $output .= '</b></i>'; $state = ''; }
1039 else if ($state == 'both')
1040 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1041 else # ($state == '')
1042 { $buffer = ''; $state = 'both'; }
1047 # Now close all remaining tags. Notice that the order is important.
1048 if ($state == 'b' ||
$state == 'ib')
1050 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1054 if ($state == 'both')
1055 $output .= '<b><i>'.$buffer.'</i></b>';
1061 * Replace external links
1063 * Note: this is all very hackish and the order of execution matters a lot.
1064 * Make sure to run maintenance/parserTests.php if you change this code.
1068 function replaceExternalLinks( $text ) {
1070 $fname = 'Parser::replaceExternalLinks';
1071 wfProfileIn( $fname );
1073 $sk =& $this->mOptions
->getSkin();
1075 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1077 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1080 while ( $i<count( $bits ) ) {
1082 $protocol = $bits[$i++
];
1083 $text = $bits[$i++
];
1084 $trail = $bits[$i++
];
1086 # The characters '<' and '>' (which were escaped by
1087 # removeHTMLtags()) should not be included in
1088 # URLs, per RFC 2396.
1089 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1090 $text = substr($url, $m2[0][1]) . ' ' . $text;
1091 $url = substr($url, 0, $m2[0][1]);
1094 # If the link text is an image URL, replace it with an <img> tag
1095 # This happened by accident in the original parser, but some people used it extensively
1096 $img = $this->maybeMakeExternalImage( $text );
1097 if ( $img !== false ) {
1103 # Set linktype for CSS - if URL==text, link is essentially free
1104 $linktype = ($text == $url) ?
'free' : 'text';
1106 # No link text, e.g. [http://domain.tld/some.link]
1107 if ( $text == '' ) {
1108 # Autonumber if allowed
1109 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1110 $text = '[' . ++
$this->mAutonumber
. ']';
1111 $linktype = 'autonumber';
1113 # Otherwise just use the URL
1114 $text = htmlspecialchars( $url );
1118 # Have link text, e.g. [http://domain.tld/some.link text]s
1120 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1123 $text = $wgContLang->markNoConversion($text);
1125 # Replace & from obsolete syntax with &.
1126 # All HTML entities will be escaped by makeExternalLink()
1127 $url = str_replace( '&', '&', $url );
1128 # Replace unnecessary URL escape codes with the referenced character
1129 # This prevents spammers from hiding links from the filters
1130 $url = Parser
::replaceUnusualEscapes( $url );
1132 # Process the trail (i.e. everything after this link up until start of the next link),
1133 # replacing any non-bracketed links
1134 $trail = $this->replaceFreeExternalLinks( $trail );
1136 # Use the encoded URL
1137 # This means that users can paste URLs directly into the text
1138 # Funny characters like ö aren't valid in URLs anyway
1139 # This was changed in August 2004
1140 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1142 # Register link in the output object
1143 $this->mOutput
->addExternalLink( $url );
1146 wfProfileOut( $fname );
1151 * Replace anything that looks like a URL with a link
1154 function replaceFreeExternalLinks( $text ) {
1156 $fname = 'Parser::replaceFreeExternalLinks';
1157 wfProfileIn( $fname );
1159 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1160 $s = array_shift( $bits );
1163 $sk =& $this->mOptions
->getSkin();
1165 while ( $i < count( $bits ) ){
1166 $protocol = $bits[$i++
];
1167 $remainder = $bits[$i++
];
1169 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1170 # Found some characters after the protocol that look promising
1171 $url = $protocol . $m[1];
1174 # The characters '<' and '>' (which were escaped by
1175 # removeHTMLtags()) should not be included in
1176 # URLs, per RFC 2396.
1177 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1178 $trail = substr($url, $m2[0][1]) . $trail;
1179 $url = substr($url, 0, $m2[0][1]);
1182 # Move trailing punctuation to $trail
1184 # If there is no left bracket, then consider right brackets fair game too
1185 if ( strpos( $url, '(' ) === false ) {
1189 $numSepChars = strspn( strrev( $url ), $sep );
1190 if ( $numSepChars ) {
1191 $trail = substr( $url, -$numSepChars ) . $trail;
1192 $url = substr( $url, 0, -$numSepChars );
1195 # Replace & from obsolete syntax with &.
1196 # All HTML entities will be escaped by makeExternalLink()
1197 # or maybeMakeExternalImage()
1198 $url = str_replace( '&', '&', $url );
1199 # Replace unnecessary URL escape codes with their equivalent characters
1200 $url = Parser
::replaceUnusualEscapes( $url );
1202 # Is this an external image?
1203 $text = $this->maybeMakeExternalImage( $url );
1204 if ( $text === false ) {
1205 # Not an image, make a link
1206 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1207 # Register it in the output object
1208 $this->mOutput
->addExternalLink( $url );
1210 $s .= $text . $trail;
1212 $s .= $protocol . $remainder;
1215 wfProfileOut( $fname );
1220 * Replace unusual URL escape codes with their equivalent characters
1225 function replaceUnusualEscapes( $url ) {
1226 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1227 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1231 * Callback function used in replaceUnusualEscapes().
1232 * Replaces unusual URL escape codes with their equivalent character
1236 function replaceUnusualEscapesCallback( $matches ) {
1237 $char = urldecode( $matches[0] );
1238 $ord = ord( $char );
1239 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1240 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1241 // No, shouldn't be escaped
1244 // Yes, leave it escaped
1250 * make an image if it's allowed, either through the global
1251 * option or through the exception
1254 function maybeMakeExternalImage( $url ) {
1255 $sk =& $this->mOptions
->getSkin();
1256 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1257 $imagesexception = !empty($imagesfrom);
1259 if ( $this->mOptions
->getAllowExternalImages()
1260 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1261 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1263 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1270 * Process [[ ]] wikilinks
1274 function replaceInternalLinks( $s ) {
1276 static $fname = 'Parser::replaceInternalLinks' ;
1278 wfProfileIn( $fname );
1280 wfProfileIn( $fname.'-setup' );
1282 # the % is needed to support urlencoded titles as well
1283 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1285 $sk =& $this->mOptions
->getSkin();
1287 #split the entire text string on occurences of [[
1288 $a = explode( '[[', ' ' . $s );
1289 #get the first element (all text up to first [[), and remove the space we added
1290 $s = array_shift( $a );
1291 $s = substr( $s, 1 );
1293 # Match a link having the form [[namespace:link|alternate]]trail
1295 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1296 # Match cases where there is no "]]", which might still be images
1297 static $e1_img = FALSE;
1298 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1299 # Match the end of a line for a word that's not followed by whitespace,
1300 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1301 $e2 = wfMsgForContent( 'linkprefix' );
1303 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1305 if( is_null( $this->mTitle
) ) {
1306 wfDebugDieBacktrace( 'nooo' );
1308 $nottalk = !$this->mTitle
->isTalkPage();
1310 if ( $useLinkPrefixExtension ) {
1311 if ( preg_match( $e2, $s, $m ) ) {
1312 $first_prefix = $m[2];
1314 $first_prefix = false;
1320 $selflink = $this->mTitle
->getPrefixedText();
1321 wfProfileOut( $fname.'-setup' );
1323 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1324 $useSubpages = $this->areSubpagesAllowed();
1326 # Loop for each link
1327 for ($k = 0; isset( $a[$k] ); $k++
) {
1329 if ( $useLinkPrefixExtension ) {
1330 wfProfileIn( $fname.'-prefixhandling' );
1331 if ( preg_match( $e2, $s, $m ) ) {
1339 $prefix = $first_prefix;
1340 $first_prefix = false;
1342 wfProfileOut( $fname.'-prefixhandling' );
1345 $might_be_img = false;
1347 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1349 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1350 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1351 # the real problem is with the $e1 regex
1354 # Still some problems for cases where the ] is meant to be outside punctuation,
1355 # and no image is in sight. See bug 2095.
1357 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1358 $text .= ']'; # so that replaceExternalLinks($text) works later
1361 # fix up urlencoded title texts
1362 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1364 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1365 $might_be_img = true;
1367 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1369 } else { # Invalid form; output directly
1370 $s .= $prefix . '[[' . $line ;
1374 # Don't allow internal links to pages containing
1375 # PROTO: where PROTO is a valid URL protocol; these
1376 # should be external links.
1377 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1378 $s .= $prefix . '[[' . $line ;
1382 # Make subpage if necessary
1383 if( $useSubpages ) {
1384 $link = $this->maybeDoSubpageLink( $m[1], $text );
1389 $noforce = (substr($m[1], 0, 1) != ':');
1391 # Strip off leading ':'
1392 $link = substr($link, 1);
1395 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1397 $s .= $prefix . '[[' . $line;
1401 #check other language variants of the link
1402 #if the article does not exist
1403 if( $checkVariantLink
1404 && $nt->getArticleID() == 0 ) {
1405 $wgContLang->findVariantLink($link, $nt);
1408 $ns = $nt->getNamespace();
1409 $iw = $nt->getInterWiki();
1411 if ($might_be_img) { # if this is actually an invalid link
1412 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1414 while (isset ($a[$k+
1]) ) {
1415 #look at the next 'line' to see if we can close it there
1416 $spliced = array_splice( $a, $k +
1, 1 );
1417 $next_line = array_shift( $spliced );
1418 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1419 # the first ]] closes the inner link, the second the image
1421 $text .= '[[' . $m[1];
1424 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1425 #if there's exactly one ]] that's fine, we'll keep looking
1426 $text .= '[[' . $m[0];
1428 #if $next_line is invalid too, we need look no further
1429 $text .= '[[' . $next_line;
1434 # we couldn't find the end of this imageLink, so output it raw
1435 #but don't ignore what might be perfectly normal links in the text we've examined
1436 $text = $this->replaceInternalLinks($text);
1437 $s .= $prefix . '[[' . $link . '|' . $text;
1438 # note: no $trail, because without an end, there *is* no trail
1441 } else { #it's not an image, so output it raw
1442 $s .= $prefix . '[[' . $link . '|' . $text;
1443 # note: no $trail, because without an end, there *is* no trail
1448 $wasblank = ( '' == $text );
1449 if( $wasblank ) $text = $link;
1452 # Link not escaped by : , create the various objects
1456 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1457 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1458 $s = rtrim($s . "\n");
1459 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1463 if ( $ns == NS_IMAGE
) {
1464 wfProfileIn( "$fname-image" );
1465 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1466 # recursively parse links inside the image caption
1467 # actually, this will parse them in any other parameters, too,
1468 # but it might be hard to fix that, and it doesn't matter ATM
1469 $text = $this->replaceExternalLinks($text);
1470 $text = $this->replaceInternalLinks($text);
1472 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1473 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1474 $this->mOutput
->addImage( $nt->getDBkey() );
1476 wfProfileOut( "$fname-image" );
1479 wfProfileOut( "$fname-image" );
1483 if ( $ns == NS_CATEGORY
) {
1484 wfProfileIn( "$fname-category" );
1485 $s = rtrim($s . "\n"); # bug 87
1488 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1489 $sortkey = $this->mTitle
->getText();
1491 $sortkey = $this->mTitle
->getPrefixedText();
1496 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1497 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1498 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1501 * Strip the whitespace Category links produce, see bug 87
1502 * @todo We might want to use trim($tmp, "\n") here.
1504 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1506 wfProfileOut( "$fname-category" );
1511 if( ( $nt->getPrefixedText() === $selflink ) &&
1512 ( $nt->getFragment() === '' ) ) {
1513 # Self-links are handled specially; generally de-link and change to bold.
1514 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1518 # Special and Media are pseudo-namespaces; no pages actually exist in them
1519 if( $ns == NS_MEDIA
) {
1520 $link = $sk->makeMediaLinkObj( $nt, $text );
1521 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1522 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1523 $this->mOutput
->addImage( $nt->getDBkey() );
1525 } elseif( $ns == NS_SPECIAL
) {
1526 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1528 } elseif( $ns == NS_IMAGE
) {
1529 $img = Image
::newFromTitle( $nt );
1530 if( $img->exists() ) {
1531 // Force a blue link if the file exists; may be a remote
1532 // upload on the shared repository, and we want to see its
1533 // auto-generated page.
1534 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1538 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1540 wfProfileOut( $fname );
1545 * Make a link placeholder. The text returned can be later resolved to a real link with
1546 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1547 * parsing of interwiki links, and secondly to allow all extistence checks and
1548 * article length checks (for stub links) to be bundled into a single query.
1551 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1552 if ( ! is_object($nt) ) {
1554 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1556 # Separate the link trail from the rest of the link
1557 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1559 if ( $nt->isExternal() ) {
1560 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1561 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1562 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1564 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1565 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1566 $this->mLinkHolders
['queries'][] = $query;
1567 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1568 $this->mLinkHolders
['titles'][] = $nt;
1570 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1577 * Render a forced-blue link inline; protect against double expansion of
1578 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1579 * Since this little disaster has to split off the trail text to avoid
1580 * breaking URLs in the following text without breaking trails on the
1581 * wiki links, it's been made into a horrible function.
1584 * @param string $text
1585 * @param string $query
1586 * @param string $trail
1587 * @param string $prefix
1588 * @return string HTML-wikitext mix oh yuck
1590 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1591 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1592 $sk =& $this->mOptions
->getSkin();
1593 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1594 return $this->armorLinks( $link ) . $trail;
1598 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1599 * going to go through further parsing steps before inline URL expansion.
1601 * In particular this is important when using action=render, which causes
1602 * full URLs to be included.
1604 * Oh man I hate our multi-layer parser!
1606 * @param string more-or-less HTML
1607 * @return string less-or-more HTML with NOPARSE bits
1609 function armorLinks( $text ) {
1610 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1611 "{$this->mUniqPrefix}NOPARSE$1", $text );
1615 * Return true if subpage links should be expanded on this page.
1618 function areSubpagesAllowed() {
1619 # Some namespaces don't allow subpages
1620 global $wgNamespacesWithSubpages;
1621 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1625 * Handle link to subpage if necessary
1626 * @param string $target the source of the link
1627 * @param string &$text the link text, modified as necessary
1628 * @return string the full name of the link
1631 function maybeDoSubpageLink($target, &$text) {
1634 # :Foobar -- override special treatment of prefix (images, language links)
1635 # /Foobar -- convert to CurrentPage/Foobar
1636 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1637 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1638 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1640 $fname = 'Parser::maybeDoSubpageLink';
1641 wfProfileIn( $fname );
1642 $ret = $target; # default return value is no change
1644 # Some namespaces don't allow subpages,
1645 # so only perform processing if subpages are allowed
1646 if( $this->areSubpagesAllowed() ) {
1647 # Look at the first character
1648 if( $target != '' && $target{0} == '/' ) {
1649 # / at end means we don't want the slash to be shown
1650 if( substr( $target, -1, 1 ) == '/' ) {
1651 $target = substr( $target, 1, -1 );
1654 $noslash = substr( $target, 1 );
1657 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1658 if( '' === $text ) {
1660 } # this might be changed for ugliness reasons
1662 # check for .. subpage backlinks
1664 $nodotdot = $target;
1665 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1667 $nodotdot = substr( $nodotdot, 3 );
1669 if($dotdotcount > 0) {
1670 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1671 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1672 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1673 # / at the end means don't show full path
1674 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1675 $nodotdot = substr( $nodotdot, 0, -1 );
1676 if( '' === $text ) {
1680 $nodotdot = trim( $nodotdot );
1681 if( $nodotdot != '' ) {
1682 $ret .= '/' . $nodotdot;
1689 wfProfileOut( $fname );
1694 * Used by doBlockLevels()
1697 /* private */ function closeParagraph() {
1699 if ( '' != $this->mLastSection
) {
1700 $result = '</' . $this->mLastSection
. ">\n";
1702 $this->mInPre
= false;
1703 $this->mLastSection
= '';
1706 # getCommon() returns the length of the longest common substring
1707 # of both arguments, starting at the beginning of both.
1709 /* private */ function getCommon( $st1, $st2 ) {
1710 $fl = strlen( $st1 );
1711 $shorter = strlen( $st2 );
1712 if ( $fl < $shorter ) { $shorter = $fl; }
1714 for ( $i = 0; $i < $shorter; ++
$i ) {
1715 if ( $st1{$i} != $st2{$i} ) { break; }
1719 # These next three functions open, continue, and close the list
1720 # element appropriate to the prefix character passed into them.
1722 /* private */ function openList( $char ) {
1723 $result = $this->closeParagraph();
1725 if ( '*' == $char ) { $result .= '<ul><li>'; }
1726 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1727 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1728 else if ( ';' == $char ) {
1729 $result .= '<dl><dt>';
1730 $this->mDTopen
= true;
1732 else { $result = '<!-- ERR 1 -->'; }
1737 /* private */ function nextItem( $char ) {
1738 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1739 else if ( ':' == $char ||
';' == $char ) {
1741 if ( $this->mDTopen
) { $close = '</dt>'; }
1742 if ( ';' == $char ) {
1743 $this->mDTopen
= true;
1744 return $close . '<dt>';
1746 $this->mDTopen
= false;
1747 return $close . '<dd>';
1750 return '<!-- ERR 2 -->';
1753 /* private */ function closeList( $char ) {
1754 if ( '*' == $char ) { $text = '</li></ul>'; }
1755 else if ( '#' == $char ) { $text = '</li></ol>'; }
1756 else if ( ':' == $char ) {
1757 if ( $this->mDTopen
) {
1758 $this->mDTopen
= false;
1759 $text = '</dt></dl>';
1761 $text = '</dd></dl>';
1764 else { return '<!-- ERR 3 -->'; }
1770 * Make lists from lines starting with ':', '*', '#', etc.
1773 * @return string the lists rendered as HTML
1775 function doBlockLevels( $text, $linestart ) {
1776 $fname = 'Parser::doBlockLevels';
1777 wfProfileIn( $fname );
1779 # Parsing through the text line by line. The main thing
1780 # happening here is handling of block-level elements p, pre,
1781 # and making lists from lines starting with * # : etc.
1783 $textLines = explode( "\n", $text );
1785 $lastPrefix = $output = '';
1786 $this->mDTopen
= $inBlockElem = false;
1788 $paragraphStack = false;
1790 if ( !$linestart ) {
1791 $output .= array_shift( $textLines );
1793 foreach ( $textLines as $oLine ) {
1794 $lastPrefixLength = strlen( $lastPrefix );
1795 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1796 $preOpenMatch = preg_match('/<pre/i', $oLine );
1797 if ( !$this->mInPre
) {
1798 # Multiple prefixes may abut each other for nested lists.
1799 $prefixLength = strspn( $oLine, '*#:;' );
1800 $pref = substr( $oLine, 0, $prefixLength );
1803 $pref2 = str_replace( ';', ':', $pref );
1804 $t = substr( $oLine, $prefixLength );
1805 $this->mInPre
= !empty($preOpenMatch);
1807 # Don't interpret any other prefixes in preformatted text
1809 $pref = $pref2 = '';
1814 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1815 # Same as the last item, so no need to deal with nesting or opening stuff
1816 $output .= $this->nextItem( substr( $pref, -1 ) );
1817 $paragraphStack = false;
1819 if ( substr( $pref, -1 ) == ';') {
1820 # The one nasty exception: definition lists work like this:
1821 # ; title : definition text
1822 # So we check for : in the remainder text to split up the
1823 # title and definition, without b0rking links.
1825 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1827 $output .= $term . $this->nextItem( ':' );
1830 } elseif( $prefixLength ||
$lastPrefixLength ) {
1831 # Either open or close a level...
1832 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1833 $paragraphStack = false;
1835 while( $commonPrefixLength < $lastPrefixLength ) {
1836 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1837 --$lastPrefixLength;
1839 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1840 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1842 while ( $prefixLength > $commonPrefixLength ) {
1843 $char = substr( $pref, $commonPrefixLength, 1 );
1844 $output .= $this->openList( $char );
1846 if ( ';' == $char ) {
1847 # FIXME: This is dupe of code above
1848 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1850 $output .= $term . $this->nextItem( ':' );
1853 ++
$commonPrefixLength;
1855 $lastPrefix = $pref2;
1857 if( 0 == $prefixLength ) {
1858 wfProfileIn( "$fname-paragraph" );
1859 # No prefix (not in list)--go to paragraph mode
1860 // XXX: use a stack for nestable elements like span, table and div
1861 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1862 $closematch = preg_match(
1863 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1864 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1865 if ( $openmatch or $closematch ) {
1866 $paragraphStack = false;
1867 $output .= $this->closeParagraph();
1868 if ( $preOpenMatch and !$preCloseMatch ) {
1869 $this->mInPre
= true;
1871 if ( $closematch ) {
1872 $inBlockElem = false;
1874 $inBlockElem = true;
1876 } else if ( !$inBlockElem && !$this->mInPre
) {
1877 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1879 if ($this->mLastSection
!= 'pre') {
1880 $paragraphStack = false;
1881 $output .= $this->closeParagraph().'<pre>';
1882 $this->mLastSection
= 'pre';
1884 $t = substr( $t, 1 );
1887 if ( '' == trim($t) ) {
1888 if ( $paragraphStack ) {
1889 $output .= $paragraphStack.'<br />';
1890 $paragraphStack = false;
1891 $this->mLastSection
= 'p';
1893 if ($this->mLastSection
!= 'p' ) {
1894 $output .= $this->closeParagraph();
1895 $this->mLastSection
= '';
1896 $paragraphStack = '<p>';
1898 $paragraphStack = '</p><p>';
1902 if ( $paragraphStack ) {
1903 $output .= $paragraphStack;
1904 $paragraphStack = false;
1905 $this->mLastSection
= 'p';
1906 } else if ($this->mLastSection
!= 'p') {
1907 $output .= $this->closeParagraph().'<p>';
1908 $this->mLastSection
= 'p';
1913 wfProfileOut( "$fname-paragraph" );
1915 // somewhere above we forget to get out of pre block (bug 785)
1916 if($preCloseMatch && $this->mInPre
) {
1917 $this->mInPre
= false;
1919 if ($paragraphStack === false) {
1923 while ( $prefixLength ) {
1924 $output .= $this->closeList( $pref2{$prefixLength-1} );
1927 if ( '' != $this->mLastSection
) {
1928 $output .= '</' . $this->mLastSection
. '>';
1929 $this->mLastSection
= '';
1932 wfProfileOut( $fname );
1937 * Split up a string on ':', ignoring any occurences inside
1938 * <a>..</a> or <span>...</span>
1939 * @param string $str the string to split
1940 * @param string &$before set to everything before the ':'
1941 * @param string &$after set to everything after the ':'
1942 * return string the position of the ':', or false if none found
1944 function findColonNoLinks($str, &$before, &$after) {
1945 # I wonder if we should make this count all tags, not just <a>
1946 # and <span>. That would prevent us from matching a ':' that
1947 # comes in the middle of italics other such formatting....
1949 $fname = 'Parser::findColonNoLinks';
1950 wfProfileIn( $fname );
1953 $colon = strpos($str, ':', $pos);
1955 if ($colon !== false) {
1956 $before = substr($str, 0, $colon);
1957 $after = substr($str, $colon +
1);
1959 # Skip any ':' within <a> or <span> pairs
1960 $a = substr_count($before, '<a');
1961 $s = substr_count($before, '<span');
1962 $ca = substr_count($before, '</a>');
1963 $cs = substr_count($before, '</span>');
1965 if ($a <= $ca and $s <= $cs) {
1966 # Tags are balanced before ':'; ok
1971 } while ($colon !== false);
1972 wfProfileOut( $fname );
1977 * Return value of a magic variable (like PAGENAME)
1981 function getVariableValue( $index ) {
1982 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1985 * Some of these require message or data lookups and can be
1986 * expensive to check many times.
1988 static $varCache = array();
1989 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1990 if ( isset( $varCache[$index] ) )
1991 return $varCache[$index];
1994 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1997 case MAG_CURRENTMONTH
:
1998 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1999 case MAG_CURRENTMONTHNAME
:
2000 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2001 case MAG_CURRENTMONTHNAMEGEN
:
2002 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2003 case MAG_CURRENTMONTHABBREV
:
2004 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2005 case MAG_CURRENTDAY
:
2006 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2007 case MAG_CURRENTDAY2
:
2008 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2010 return $this->mTitle
->getText();
2012 return $this->mTitle
->getPartialURL();
2013 case MAG_FULLPAGENAME
:
2014 return $this->mTitle
->getPrefixedText();
2015 case MAG_FULLPAGENAMEE
:
2016 return $this->mTitle
->getPrefixedURL();
2017 case MAG_REVISIONID
:
2018 return $this->mRevisionId
;
2020 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2021 case MAG_NAMESPACEE
:
2022 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2023 case MAG_CURRENTDAYNAME
:
2024 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2025 case MAG_CURRENTYEAR
:
2026 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2027 case MAG_CURRENTTIME
:
2028 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2029 case MAG_CURRENTWEEK
:
2030 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2031 // int to remove the padding
2032 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2033 case MAG_CURRENTDOW
:
2034 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2035 case MAG_NUMBEROFARTICLES
:
2036 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2037 case MAG_NUMBEROFFILES
:
2038 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2043 case MAG_SERVERNAME
:
2044 return $wgServerName;
2045 case MAG_SCRIPTPATH
:
2046 return $wgScriptPath;
2049 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2057 * initialise the magic variables (like CURRENTMONTHNAME)
2061 function initialiseVariables() {
2062 $fname = 'Parser::initialiseVariables';
2063 wfProfileIn( $fname );
2064 global $wgVariableIDs;
2065 $this->mVariables
= array();
2066 foreach ( $wgVariableIDs as $id ) {
2067 $mw =& MagicWord
::get( $id );
2068 $mw->addToArray( $this->mVariables
, $id );
2070 wfProfileOut( $fname );
2074 * parse any parentheses in format ((title|part|part))
2075 * and call callbacks to get a replacement text for any found piece
2077 * @param string $text The text to parse
2078 * @param array $callbacks rules in form:
2079 * '{' => array( # opening parentheses
2080 * 'end' => '}', # closing parentheses
2081 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2082 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2087 function replace_callback ($text, $callbacks) {
2088 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2089 $lastOpeningBrace = -1; # last not closed parentheses
2091 for ($i = 0; $i < strlen($text); $i++
) {
2092 # check for any opening brace
2095 foreach ($callbacks as $key => $value) {
2096 $pos = strpos ($text, $key, $i);
2097 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2103 if ($lastOpeningBrace >= 0) {
2104 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2106 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2111 $pos = strpos ($text, '|', $i);
2113 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2124 # found openning brace, lets add it to parentheses stack
2125 if (null != $rule) {
2126 $piece = array('brace' => $text[$i],
2127 'braceEnd' => $rule['end'],
2132 # count openning brace characters
2133 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2138 $piece['startAt'] = $i+
1;
2139 $piece['partStart'] = $i+
1;
2141 # we need to add to stack only if openning brace count is enough for any given rule
2142 foreach ($rule['cb'] as $cnt => $fn) {
2143 if ($piece['count'] >= $cnt) {
2144 $lastOpeningBrace ++
;
2145 $openingBraceStack[$lastOpeningBrace] = $piece;
2152 else if ($lastOpeningBrace >= 0) {
2153 # first check if it is a closing brace
2154 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2155 # lets check if it is enough characters for closing brace
2157 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2160 # if there are more closing parentheses than opening ones, we parse less
2161 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2162 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2164 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2166 $matchingCallback = null;
2167 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2168 if ($count >= $cnt && $matchingCount < $cnt) {
2169 $matchingCount = $cnt;
2170 $matchingCallback = $fn;
2174 if ($matchingCount == 0) {
2179 # lets set a title or last part (if '|' was found)
2180 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2181 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2183 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2185 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2186 $pieceEnd = $i +
$matchingCount;
2188 if( is_callable( $matchingCallback ) ) {
2190 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2191 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2192 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2193 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2195 # finally we can call a user callback and replace piece of text
2196 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2197 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2198 $i = $pieceStart +
strlen($replaceWith) - 1;
2201 # null value for callback means that parentheses should be parsed, but not replaced
2202 $i +
= $matchingCount - 1;
2205 # reset last openning parentheses, but keep it in case there are unused characters
2206 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2207 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2208 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2211 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2212 $openingBraceStack[$lastOpeningBrace--] = null;
2214 if ($matchingCount < $piece['count']) {
2215 $piece['count'] -= $matchingCount;
2216 $piece['startAt'] -= $matchingCount;
2217 $piece['partStart'] = $piece['startAt'];
2218 # do we still qualify for any callback with remaining count?
2219 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2220 if ($piece['count'] >= $cnt) {
2221 $lastOpeningBrace ++
;
2222 $openingBraceStack[$lastOpeningBrace] = $piece;
2230 # lets set a title if it is a first separator, or next part otherwise
2231 if ($text[$i] == '|') {
2232 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2233 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2234 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2237 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2239 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2248 * Replace magic variables, templates, and template arguments
2249 * with the appropriate text. Templates are substituted recursively,
2250 * taking care to avoid infinite loops.
2252 * Note that the substitution depends on value of $mOutputType:
2253 * OT_WIKI: only {{subst:}} templates
2254 * OT_MSG: only magic variables
2255 * OT_HTML: all templates and magic variables
2257 * @param string $tex The text to transform
2258 * @param array $args Key-value pairs representing template parameters to substitute
2259 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2262 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2263 # Prevent too big inclusions
2264 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2268 $fname = 'Parser::replaceVariables';
2269 wfProfileIn( $fname );
2271 # This function is called recursively. To keep track of arguments we need a stack:
2272 array_push( $this->mArgStack
, $args );
2274 $braceCallbacks = array();
2276 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2278 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2279 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2281 $callbacks = array();
2282 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2283 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2284 $text = $this->replace_callback ($text, $callbacks);
2286 array_pop( $this->mArgStack
);
2288 wfProfileOut( $fname );
2293 * Replace magic variables
2296 function variableSubstitution( $matches ) {
2297 $fname = 'Parser::variableSubstitution';
2298 $varname = $matches[1];
2299 wfProfileIn( $fname );
2300 if ( !$this->mVariables
) {
2301 $this->initialiseVariables();
2304 if ( $this->mOutputType
== OT_WIKI
) {
2305 # Do only magic variables prefixed by SUBST
2306 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2307 if (!$mwSubst->matchStartAndRemove( $varname ))
2309 # Note that if we don't substitute the variable below,
2310 # we don't remove the {{subst:}} magic word, in case
2311 # it is a template rather than a magic variable.
2313 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2314 $id = $this->mVariables
[$varname];
2315 $text = $this->getVariableValue( $id );
2316 $this->mOutput
->mContainsOldMagic
= true;
2318 $text = $matches[0];
2320 wfProfileOut( $fname );
2324 # Split template arguments
2325 function getTemplateArgs( $argsString ) {
2326 if ( $argsString === '' ) {
2330 $args = explode( '|', substr( $argsString, 1 ) );
2332 # If any of the arguments contains a '[[' but no ']]', it needs to be
2333 # merged with the next arg because the '|' character between belongs
2334 # to the link syntax and not the template parameter syntax.
2335 $argc = count($args);
2337 for ( $i = 0; $i < $argc-1; $i++
) {
2338 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2339 $args[$i] .= '|'.$args[$i+
1];
2340 array_splice($args, $i+
1, 1);
2350 * Return the text of a template, after recursively
2351 * replacing any variables or templates within the template.
2353 * @param array $piece The parts of the template
2354 * $piece['text']: matched text
2355 * $piece['title']: the title, i.e. the part before the |
2356 * $piece['parts']: the parameter array
2357 * @return string the text of the template
2360 function braceSubstitution( $piece ) {
2362 $fname = 'Parser::braceSubstitution';
2363 wfProfileIn( $fname );
2366 $found = false; # $text has been filled
2367 $nowiki = false; # wiki markup in $text should be escaped
2368 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2369 $noargs = false; # Don't replace triple-brace arguments in $text
2370 $replaceHeadings = false; # Make the edit section links go to the template not the article
2371 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2372 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2374 # Title object, where $text came from
2379 # $part1 is the bit before the first |, and must contain only title characters
2380 # $args is a list of arguments, starting from index 0, not including $part1
2382 $part1 = $piece['title'];
2383 # If the third subpattern matched anything, it will start with |
2385 if (null == $piece['parts']) {
2386 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2387 if ($replaceWith != $piece['text']) {
2388 $text = $replaceWith;
2395 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2396 $argc = count( $args );
2400 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2401 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2402 # One of two possibilities is true:
2403 # 1) Found SUBST but not in the PST phase
2404 # 2) Didn't find SUBST and in the PST phase
2405 # In either case, return without further processing
2406 $text = $piece['text'];
2413 # MSG, MSGNW, INT and RAW
2416 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2417 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2420 # Remove obsolete MSG:
2421 $mwMsg =& MagicWord
::get( MAG_MSG
);
2422 $mwMsg->matchStartAndRemove( $part1 );
2426 $mwRaw =& MagicWord
::get( MAG_RAW
);
2427 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2428 $forceRawInterwiki = true;
2431 # Check if it is an internal message
2432 $mwInt =& MagicWord
::get( MAG_INT
);
2433 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2434 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2435 $text = $linestart . wfMsgReal( $part1, $args, true );
2443 # Check for NS: (namespace expansion)
2444 $mwNs = MagicWord
::get( MAG_NS
);
2445 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2446 if ( intval( $part1 ) ||
$part1 == "0" ) {
2447 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2450 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2451 if ( !is_null( $index ) ) {
2452 $text = $linestart . $wgContLang->getNsText( $index );
2459 # LCFIRST, UCFIRST, LC and UC
2461 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2462 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2463 $lc =& MagicWord
::get( MAG_LC
);
2464 $uc =& MagicWord
::get( MAG_UC
);
2465 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2466 $text = $linestart . $wgContLang->lcfirst( $part1 );
2468 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2469 $text = $linestart . $wgContLang->ucfirst( $part1 );
2471 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2472 $text = $linestart . $wgContLang->lc( $part1 );
2474 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2475 $text = $linestart . $wgContLang->uc( $part1 );
2480 # LOCALURL and FULLURL
2482 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2483 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2484 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2485 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2488 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2489 $func = 'getLocalURL';
2490 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2491 $func = 'escapeLocalURL';
2492 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2493 $func = 'getFullURL';
2494 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2495 $func = 'escapeFullURL';
2500 if ( $func !== false ) {
2501 $title = Title
::newFromText( $part1 );
2502 if ( !is_null( $title ) ) {
2504 $text = $linestart . $title->$func( $args[0] );
2506 $text = $linestart . $title->$func();
2514 if ( !$found && $argc == 1 ) {
2515 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2516 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2517 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2523 if ( !$found && $argc >= 2 ) {
2524 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2525 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2526 if ($argc==2) {$args[2]=$args[1];}
2527 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2532 # Template table test
2534 # Did we encounter this template already? If yes, it is in the cache
2535 # and we need to check for loops.
2536 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2539 # Infinite loop test
2540 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2544 $text = $linestart .
2545 '{{' . $part1 . '}}' .
2546 '<!-- WARNING: template loop detected -->';
2547 wfDebug( "$fname: template loop broken at '$part1'\n" );
2549 # set $text to cached message.
2550 $text = $linestart . $this->mTemplates
[$piece['title']];
2554 # Load from database
2555 $lastPathLevel = $this->mTemplatePath
;
2558 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2559 if ($subpage !== '') {
2560 $ns = $this->mTitle
->getNamespace();
2562 $title = Title
::newFromText( $part1, $ns );
2564 if ( !is_null( $title ) ) {
2565 if ( !$title->isExternal() ) {
2566 # Check for excessive inclusion
2567 $dbk = $title->getPrefixedDBkey();
2568 if ( $this->incrementIncludeCount( $dbk ) ) {
2569 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2570 # Capture special page output
2571 $text = SpecialPage
::capturePath( $title );
2572 if ( is_string( $text ) ) {
2577 $this->disableCache();
2580 $articleContent = $this->fetchTemplate( $title );
2581 if ( $articleContent !== false ) {
2583 $text = $articleContent;
2584 $replaceHeadings = true;
2589 # If the title is valid but undisplayable, make a link to it
2590 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2591 $text = '[['.$title->getPrefixedText().']]';
2594 } elseif ( $title->isTrans() ) {
2595 // Interwiki transclusion
2596 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2597 $text = $this->interwikiTransclude( $title, 'render' );
2601 $text = $this->interwikiTransclude( $title, 'raw' );
2602 $replaceHeadings = true;
2607 # Template cache array insertion
2608 # Use the original $piece['title'] not the mangled $part1, so that
2609 # modifiers such as RAW: produce separate cache entries
2611 $this->mTemplates
[$piece['title']] = $text;
2612 $text = $linestart . $text;
2617 # Recursive parsing, escaping and link table handling
2618 # Only for HTML output
2619 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2620 $text = wfEscapeWikiText( $text );
2621 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2623 # Clean up argument array
2624 $assocArgs = array();
2626 foreach( $args as $arg ) {
2627 $eqpos = strpos( $arg, '=' );
2628 if ( $eqpos === false ) {
2629 $assocArgs[$index++
] = $arg;
2631 $name = trim( substr( $arg, 0, $eqpos ) );
2632 $value = trim( substr( $arg, $eqpos+
1 ) );
2633 if ( $value === false ) {
2636 if ( $name !== false ) {
2637 $assocArgs[$name] = $value;
2642 # Add a new element to the templace recursion path
2643 $this->mTemplatePath
[$part1] = 1;
2647 # If there are any <onlyinclude> tags, only include them
2648 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2649 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2651 foreach ($m[1] as $piece)
2654 # Remove <noinclude> sections and <includeonly> tags
2655 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2656 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2658 if( $this->mOutputType
== OT_HTML
) {
2659 # Strip <nowiki>, <pre>, etc.
2660 $text = $this->strip( $text, $this->mStripState
);
2661 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2663 $text = $this->replaceVariables( $text, $assocArgs );
2665 # If the template begins with a table or block-level
2666 # element, it should be treated as beginning a new line.
2667 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2668 $text = "\n" . $text;
2670 } elseif ( !$noargs ) {
2671 # $noparse and !$noargs
2672 # Just replace the arguments, not any double-brace items
2673 # This is used for rendered interwiki transclusion
2674 $text = $this->replaceVariables( $text, $assocArgs, true );
2677 # Prune lower levels off the recursion check path
2678 $this->mTemplatePath
= $lastPathLevel;
2681 wfProfileOut( $fname );
2682 return $piece['text'];
2685 # Replace raw HTML by a placeholder
2686 # Add a blank line preceding, to prevent it from mucking up
2687 # immediately preceding headings
2688 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2690 # replace ==section headers==
2691 # XXX this needs to go away once we have a better parser.
2692 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2693 if( !is_null( $title ) )
2694 $encodedname = base64_encode($title->getPrefixedDBkey());
2696 $encodedname = base64_encode("");
2697 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2698 PREG_SPLIT_DELIM_CAPTURE
);
2701 for( $i = 0; $i < count($m); $i +
= 2 ) {
2703 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2705 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2709 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2710 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2711 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2719 # Prune lower levels off the recursion check path
2720 $this->mTemplatePath
= $lastPathLevel;
2723 wfProfileOut( $fname );
2724 return $piece['text'];
2726 wfProfileOut( $fname );
2732 * Fetch the unparsed text of a template and register a reference to it.
2734 function fetchTemplate( $title ) {
2736 // Loop to fetch the article, with up to 1 redirect
2737 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2738 $rev = Revision
::newFromTitle( $title );
2739 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2743 $text = $rev->getText();
2744 if ( $text === false ) {
2748 $title = Title
::newFromRedirect( $text );
2754 * Transclude an interwiki link.
2756 function interwikiTransclude( $title, $action ) {
2757 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2759 if (!$wgEnableScaryTranscluding)
2760 return wfMsg('scarytranscludedisabled');
2762 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2763 // But we'll handle it generally anyway
2764 if ( $title->getNamespace() ) {
2765 // Use the canonical namespace, which should work anywhere
2766 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2768 $articleName = $title->getDBkey();
2771 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2772 $url .= "?action=$action";
2773 if (strlen($url) > 255)
2774 return wfMsg('scarytranscludetoolong');
2775 return $this->fetchScaryTemplateMaybeFromCache($url);
2778 function fetchScaryTemplateMaybeFromCache($url) {
2779 global $wgTranscludeCacheExpiry;
2780 $dbr =& wfGetDB(DB_SLAVE
);
2781 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2782 array('tc_url' => $url));
2784 $time = $obj->tc_time
;
2785 $text = $obj->tc_contents
;
2786 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2791 $text = wfGetHTTP($url);
2793 return wfMsg('scarytranscludefailed', $url);
2795 $dbw =& wfGetDB(DB_MASTER
);
2796 $dbw->replace('transcache', array('tc_url'), array(
2798 'tc_time' => time(),
2799 'tc_contents' => $text));
2805 * Triple brace replacement -- used for template arguments
2808 function argSubstitution( $matches ) {
2809 $arg = trim( $matches['title'] );
2810 $text = $matches['text'];
2811 $inputArgs = end( $this->mArgStack
);
2813 if ( array_key_exists( $arg, $inputArgs ) ) {
2814 $text = $inputArgs[$arg];
2815 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2816 $text = $matches['parts'][0];
2823 * Returns true if the function is allowed to include this entity
2826 function incrementIncludeCount( $dbk ) {
2827 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2828 $this->mIncludeCount
[$dbk] = 0;
2830 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2838 * This function accomplishes several tasks:
2839 * 1) Auto-number headings if that option is enabled
2840 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2841 * 3) Add a Table of contents on the top for users who have enabled the option
2842 * 4) Auto-anchor headings
2844 * It loops through all headlines, collects the necessary data, then splits up the
2845 * string and re-inserts the newly formatted headlines.
2847 * @param string $text
2848 * @param boolean $isMain
2851 function formatHeadings( $text, $isMain=true ) {
2852 global $wgMaxTocLevel, $wgContLang;
2854 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2856 $forceTocHere = false;
2857 if( !$this->mTitle
->userCanEdit() ) {
2860 $showEditLink = $this->mOptions
->getEditSection();
2863 # Inhibit editsection links if requested in the page
2864 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2865 if( $esw->matchAndRemove( $text ) ) {
2868 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2870 $mw =& MagicWord
::get( MAG_NOTOC
);
2871 if( $mw->matchAndRemove( $text ) ) {
2875 # Get all headlines for numbering them and adding funky stuff like [edit]
2876 # links - this is for later, but we need the number of headlines right now
2877 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2879 # if there are fewer than 4 headlines in the article, do not show TOC
2880 if( $numMatches < 4 ) {
2884 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2885 # override above conditions and always show TOC at that place
2887 $mw =& MagicWord
::get( MAG_TOC
);
2888 if($mw->match( $text ) ) {
2890 $forceTocHere = true;
2892 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2893 # override above conditions and always show TOC above first header
2894 $mw =& MagicWord
::get( MAG_FORCETOC
);
2895 if ($mw->matchAndRemove( $text ) ) {
2900 # Never ever show TOC if no headers
2901 if( $numMatches < 1 ) {
2905 # We need this to perform operations on the HTML
2906 $sk =& $this->mOptions
->getSkin();
2910 $sectionCount = 0; # headlineCount excluding template sections
2912 # Ugh .. the TOC should have neat indentation levels which can be
2913 # passed to the skin functions. These are determined here
2917 $sublevelCount = array();
2918 $levelCount = array();
2925 foreach( $matches[3] as $headline ) {
2927 $templatetitle = '';
2928 $templatesection = 0;
2931 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2933 $templatetitle = base64_decode($mat[1]);
2934 $templatesection = 1 +
(int)base64_decode($mat[2]);
2935 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2939 $prevlevel = $level;
2940 $prevtoclevel = $toclevel;
2942 $level = $matches[1][$headlineCount];
2944 if( $doNumberHeadings ||
$doShowToc ) {
2946 if ( $level > $prevlevel ) {
2947 # Increase TOC level
2949 $sublevelCount[$toclevel] = 0;
2950 $toc .= $sk->tocIndent();
2952 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2953 # Decrease TOC level, find level to jump to
2955 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2956 # Can only go down to level 1
2959 for ($i = $toclevel; $i > 0; $i--) {
2960 if ( $levelCount[$i] == $level ) {
2961 # Found last matching level
2965 elseif ( $levelCount[$i] < $level ) {
2966 # Found first matching level below current level
2973 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2976 # No change in level, end TOC line
2977 $toc .= $sk->tocLineEnd();
2980 $levelCount[$toclevel] = $level;
2982 # count number of headlines for each level
2983 @$sublevelCount[$toclevel]++
;
2985 for( $i = 1; $i <= $toclevel; $i++
) {
2986 if( !empty( $sublevelCount[$i] ) ) {
2990 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2996 # The canonized header is a version of the header text safe to use for links
2997 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2998 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2999 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3001 # Remove link placeholders by the link text.
3002 # <!--LINK number-->
3004 # link text with suffix
3005 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3006 "\$this->mLinkHolders['texts'][\$1]",
3007 $canonized_headline );
3008 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3009 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3010 $canonized_headline );
3013 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3014 $tocline = trim( $canonized_headline );
3015 $canonized_headline = Sanitizer
::escapeId( $tocline );
3016 $refers[$headlineCount] = $canonized_headline;
3018 # count how many in assoc. array so we can track dupes in anchors
3019 @$refers[$canonized_headline]++
;
3020 $refcount[$headlineCount]=$refers[$canonized_headline];
3022 # Don't number the heading if it is the only one (looks silly)
3023 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3024 # the two are different if the line contains a link
3025 $headline=$numbering . ' ' . $headline;
3028 # Create the anchor for linking from the TOC to the section
3029 $anchor = $canonized_headline;
3030 if($refcount[$headlineCount] > 1 ) {
3031 $anchor .= '_' . $refcount[$headlineCount];
3033 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3034 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3036 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3037 if ( empty( $head[$headlineCount] ) ) {
3038 $head[$headlineCount] = '';
3041 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3043 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3046 # give headline the correct <h#> tag
3047 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3055 $toc .= $sk->tocUnindent( $toclevel - 1 );
3056 $toc = $sk->tocList( $toc );
3059 # split up and insert constructed headlines
3061 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3064 foreach( $blocks as $block ) {
3065 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3066 # This is the [edit] link that appears for the top block of text when
3067 # section editing is enabled
3069 # Disabled because it broke block formatting
3070 # For example, a bullet point in the top line
3071 # $full .= $sk->editSectionLink(0);
3074 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3075 # Top anchor now in skin
3079 if( !empty( $head[$i] ) ) {
3085 $mw =& MagicWord
::get( MAG_TOC
);
3086 return $mw->replace( $toc, $full );
3093 * Return an HTML link for the "ISBN 123456" text
3096 function magicISBN( $text ) {
3097 $fname = 'Parser::magicISBN';
3098 wfProfileIn( $fname );
3100 $a = split( 'ISBN ', ' '.$text );
3101 if ( count ( $a ) < 2 ) {
3102 wfProfileOut( $fname );
3105 $text = substr( array_shift( $a ), 1);
3106 $valid = '0123456789-Xx';
3108 foreach ( $a as $x ) {
3109 $isbn = $blank = '' ;
3110 while ( ' ' == $x{0} ) {
3112 $x = substr( $x, 1 );
3114 if ( $x == '' ) { # blank isbn
3115 $text .= "ISBN $blank";
3118 while ( strstr( $valid, $x{0} ) != false ) {
3120 $x = substr( $x, 1 );
3122 $num = str_replace( '-', '', $isbn );
3123 $num = str_replace( ' ', '', $num );
3124 $num = str_replace( 'x', 'X', $num );
3127 $text .= "ISBN $blank$x";
3129 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3130 $text .= '<a href="' .
3131 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3132 "\" class=\"internal\">ISBN $isbn</a>";
3136 wfProfileOut( $fname );
3141 * Return an HTML link for the "RFC 1234" text
3144 * @param string $text Text to be processed
3145 * @param string $keyword Magic keyword to use (default RFC)
3146 * @param string $urlmsg Interface message to use (default rfcurl)
3149 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3151 $valid = '0123456789';
3154 $a = split( $keyword, ' '.$text );
3155 if ( count ( $a ) < 2 ) {
3158 $text = substr( array_shift( $a ), 1);
3160 /* Check if keyword is preceed by [[.
3161 * This test is made here cause of the array_shift above
3162 * that prevent the test to be done in the foreach.
3164 if ( substr( $text, -2 ) == '[[' ) {
3168 foreach ( $a as $x ) {
3169 /* token might be empty if we have RFC RFC 1234 */
3177 /** remove and save whitespaces in $blank */
3178 while ( $x{0} == ' ' ) {
3180 $x = substr( $x, 1 );
3183 /** remove and save the rfc number in $id */
3184 while ( strstr( $valid, $x{0} ) != false ) {
3186 $x = substr( $x, 1 );
3190 /* call back stripped spaces*/
3191 $text .= $keyword.$blank.$x;
3192 } elseif( $internal ) {
3194 $text .= $keyword.$id.$x;
3196 /* build the external link*/
3197 $url = wfMsg( $urlmsg, $id);
3198 $sk =& $this->mOptions
->getSkin();
3199 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3200 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3203 /* Check if the next RFC keyword is preceed by [[ */
3204 $internal = ( substr($x,-2) == '[[' );
3210 * Transform wiki markup when saving a page by doing \r\n -> \n
3211 * conversion, substitting signatures, {{subst:}} templates, etc.
3213 * @param string $text the text to transform
3214 * @param Title &$title the Title object for the current article
3215 * @param User &$user the User object describing the current user
3216 * @param ParserOptions $options parsing options
3217 * @param bool $clearState whether to clear the parser state first
3218 * @return string the altered wiki markup
3221 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3222 $this->mOptions
= $options;
3223 $this->mTitle
=& $title;
3224 $this->mOutputType
= OT_WIKI
;
3226 if ( $clearState ) {
3227 $this->clearState();
3230 $stripState = false;
3234 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3235 $text = $this->strip( $text, $stripState, true );
3236 $text = $this->pstPass2( $text, $user );
3237 $text = $this->unstrip( $text, $stripState );
3238 $text = $this->unstripNoWiki( $text, $stripState );
3243 * Pre-save transform helper function
3246 function pstPass2( $text, &$user ) {
3247 global $wgContLang, $wgLocaltimezone;
3249 /* Note: This is the timestamp saved as hardcoded wikitext to
3250 * the database, we use $wgContLang here in order to give
3251 * everyone the same signiture and use the default one rather
3252 * than the one selected in each users preferences.
3254 if ( isset( $wgLocaltimezone ) ) {
3255 $oldtz = getenv( 'TZ' );
3256 putenv( 'TZ='.$wgLocaltimezone );
3258 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3259 ' (' . date( 'T' ) . ')';
3260 if ( isset( $wgLocaltimezone ) ) {
3261 putenv( 'TZ='.$oldtz );
3264 # Variable replacement
3265 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3266 $text = $this->replaceVariables( $text );
3269 $sigText = $this->getUserSig( $user );
3270 $text = strtr( $text, array(
3272 '~~~~' => "$sigText $d",
3276 # Context links: [[|name]] and [[name (context)|]]
3278 global $wgLegalTitleChars;
3279 $tc = "[$wgLegalTitleChars]";
3280 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3282 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3283 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3285 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3286 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3287 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3288 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3290 $t = $this->mTitle
->getText();
3291 if ( preg_match( $conpat, $t, $m ) ) {
3294 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3295 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3296 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3298 if ( '' == $context ) {
3299 $text = preg_replace( $p2, '[[\\1]]', $text );
3301 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3304 # Trim trailing whitespace
3305 # MAG_END (__END__) tag allows for trailing
3306 # whitespace to be deliberately included
3307 $text = rtrim( $text );
3308 $mw =& MagicWord
::get( MAG_END
);
3309 $mw->matchAndRemove( $text );
3315 * Fetch the user's signature text, if any, and normalize to
3316 * validated, ready-to-insert wikitext.
3322 function getUserSig( &$user ) {
3325 $username = $user->getName();
3326 $nickname = $user->getOption( 'nickname' );
3327 $nickname = $nickname === '' ?
$username : $nickname;
3329 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3330 # Sig. might contain markup; validate this
3331 if( $this->validateSig( $nickname ) !== false ) {
3332 # Validated; clean up (if needed) and return it
3333 return( $this->cleanSig( $nickname ) );
3335 # Failed to validate; fall back to the default
3336 $nickname = $username;
3337 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3341 # If we're still here, make it a link to the user page
3342 $userpage = $user->getUserPage();
3343 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3347 * Check that the user's signature contains no bad XML
3349 * @param string $text
3350 * @return mixed An expanded string, or false if invalid.
3352 function validateSig( $text ) {
3353 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3357 * Clean up signature text
3359 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3360 * 2) Substitute all transclusions
3362 * @param string $text
3363 * @return string Signature text
3365 function cleanSig( $text ) {
3366 $substWord = MagicWord
::get( MAG_SUBST
);
3367 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3368 $substText = '{{' . $substWord->getSynonym( 0 );
3370 $text = preg_replace( $substRegex, $substText, $text );
3371 $text = preg_replace( '/~{3,5}/', '', $text );
3372 $text = $this->replaceVariables( $text );
3378 * Set up some variables which are usually set up in parse()
3379 * so that an external function can call some class members with confidence
3382 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3383 $this->mTitle
=& $title;
3384 $this->mOptions
= $options;
3385 $this->mOutputType
= $outputType;
3386 if ( $clearState ) {
3387 $this->clearState();
3392 * Transform a MediaWiki message by replacing magic variables.
3394 * @param string $text the text to transform
3395 * @param ParserOptions $options options
3396 * @return string the text with variables substituted
3399 function transformMsg( $text, $options ) {
3401 static $executing = false;
3403 $fname = "Parser::transformMsg";
3405 # Guard against infinite recursion
3411 wfProfileIn($fname);
3413 $this->mTitle
= $wgTitle;
3414 $this->mOptions
= $options;
3415 $this->mOutputType
= OT_MSG
;
3416 $this->clearState();
3417 $text = $this->replaceVariables( $text );
3420 wfProfileOut($fname);
3425 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3426 * Callback will be called with the text within
3427 * Transform and return the text within
3431 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3432 * @param mixed $callback The callback function (and object) to use for the tag
3434 * @return The old value of the mTagHooks array associated with the hook
3436 function setHook( $tag, $callback ) {
3437 $oldVal = @$this->mTagHooks
[$tag];
3438 $this->mTagHooks
[$tag] = $callback;
3444 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3445 * Placeholders created in Skin::makeLinkObj()
3446 * Returns an array of links found, indexed by PDBK:
3450 * $options is a bit field, RLH_FOR_UPDATE to select for update
3452 function replaceLinkHolders( &$text, $options = 0 ) {
3454 global $wgOutputReplace;
3456 $fname = 'Parser::replaceLinkHolders';
3457 wfProfileIn( $fname );
3461 $sk =& $this->mOptions
->getSkin();
3462 $linkCache =& LinkCache
::singleton();
3464 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3465 wfProfileIn( $fname.'-check' );
3466 $dbr =& wfGetDB( DB_SLAVE
);
3467 $page = $dbr->tableName( 'page' );
3468 $threshold = $wgUser->getOption('stubthreshold');
3471 asort( $this->mLinkHolders
['namespaces'] );
3475 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3477 $title = $this->mLinkHolders
['titles'][$key];
3479 # Skip invalid entries.
3480 # Result will be ugly, but prevents crash.
3481 if ( is_null( $title ) ) {
3484 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3486 # Check if it's a static known link, e.g. interwiki
3487 if ( $title->isAlwaysKnown() ) {
3488 $colours[$pdbk] = 1;
3489 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3490 $colours[$pdbk] = 1;
3491 $this->mOutput
->addLink( $title, $id );
3492 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3493 $colours[$pdbk] = 0;
3495 # Not in the link cache, add it to the query
3496 if ( !isset( $current ) ) {
3498 $query = "SELECT page_id, page_namespace, page_title";
3499 if ( $threshold > 0 ) {
3500 $query .= ', page_len, page_is_redirect';
3502 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3503 } elseif ( $current != $ns ) {
3505 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3510 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3515 if ( $options & RLH_FOR_UPDATE
) {
3516 $query .= ' FOR UPDATE';
3519 $res = $dbr->query( $query, $fname );
3521 # Fetch data and form into an associative array
3522 # non-existent = broken
3525 while ( $s = $dbr->fetchObject($res) ) {
3526 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3527 $pdbk = $title->getPrefixedDBkey();
3528 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3529 $this->mOutput
->addLink( $title, $s->page_id
);
3531 if ( $threshold > 0 ) {
3532 $size = $s->page_len
;
3533 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3534 $colours[$pdbk] = 1;
3536 $colours[$pdbk] = 2;
3539 $colours[$pdbk] = 1;
3543 wfProfileOut( $fname.'-check' );
3545 # Construct search and replace arrays
3546 wfProfileIn( $fname.'-construct' );
3547 $wgOutputReplace = array();
3548 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3549 $pdbk = $pdbks[$key];
3550 $searchkey = "<!--LINK $key-->";
3551 $title = $this->mLinkHolders
['titles'][$key];
3552 if ( empty( $colours[$pdbk] ) ) {
3553 $linkCache->addBadLinkObj( $title );
3554 $colours[$pdbk] = 0;
3555 $this->mOutput
->addLink( $title, 0 );
3556 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3557 $this->mLinkHolders
['texts'][$key],
3558 $this->mLinkHolders
['queries'][$key] );
3559 } elseif ( $colours[$pdbk] == 1 ) {
3560 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3561 $this->mLinkHolders
['texts'][$key],
3562 $this->mLinkHolders
['queries'][$key] );
3563 } elseif ( $colours[$pdbk] == 2 ) {
3564 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3565 $this->mLinkHolders
['texts'][$key],
3566 $this->mLinkHolders
['queries'][$key] );
3569 wfProfileOut( $fname.'-construct' );
3572 wfProfileIn( $fname.'-replace' );
3574 $text = preg_replace_callback(
3575 '/(<!--LINK .*?-->)/',
3576 "wfOutputReplaceMatches",
3579 wfProfileOut( $fname.'-replace' );
3582 # Now process interwiki link holders
3583 # This is quite a bit simpler than internal links
3584 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3585 wfProfileIn( $fname.'-interwiki' );
3586 # Make interwiki link HTML
3587 $wgOutputReplace = array();
3588 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3589 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3590 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3593 $text = preg_replace_callback(
3594 '/<!--IWLINK (.*?)-->/',
3595 "wfOutputReplaceMatches",
3597 wfProfileOut( $fname.'-interwiki' );
3600 wfProfileOut( $fname );
3605 * Replace <!--LINK--> link placeholders with plain text of links
3606 * (not HTML-formatted).
3607 * @param string $text
3610 function replaceLinkHoldersText( $text ) {
3612 global $wgOutputReplace;
3614 $fname = 'Parser::replaceLinkHoldersText';
3615 wfProfileIn( $fname );
3617 $text = preg_replace_callback(
3618 '/<!--(LINK|IWLINK) (.*?)-->/',
3619 array( &$this, 'replaceLinkHoldersTextCallback' ),
3622 wfProfileOut( $fname );
3627 * @param array $matches
3631 function replaceLinkHoldersTextCallback( $matches ) {
3632 $type = $matches[1];
3634 if( $type == 'LINK' ) {
3635 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3636 return $this->mLinkHolders
['texts'][$key];
3638 } elseif( $type == 'IWLINK' ) {
3639 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3640 return $this->mInterwikiLinkHolders
['texts'][$key];
3647 * Renders an image gallery from a text with one line per image.
3648 * text labels may be given by using |-style alternative text. E.g.
3649 * Image:one.jpg|The number "1"
3650 * Image:tree.jpg|A tree
3651 * given as text will return the HTML of a gallery with two images,
3652 * labeled 'The number "1"' and
3655 function renderImageGallery( $text ) {
3657 $parserOptions = new ParserOptions
;
3658 $localParser = new Parser();
3660 $ig = new ImageGallery();
3661 $ig->setShowBytes( false );
3662 $ig->setShowFilename( false );
3663 $lines = explode( "\n", $text );
3665 foreach ( $lines as $line ) {
3666 # match lines like these:
3667 # Image:someimage.jpg|This is some image
3668 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3670 if ( count( $matches ) == 0 ) {
3673 $nt =& Title
::newFromText( $matches[1] );
3674 if( is_null( $nt ) ) {
3675 # Bogus title. Ignore these so we don't bomb out later.
3678 if ( isset( $matches[3] ) ) {
3679 $label = $matches[3];
3684 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3685 $html = $pout->getText();
3687 $ig->add( new Image( $nt ), $html );
3688 $this->mOutput
->addImage( $nt->getDBkey() );
3690 return $ig->toHTML();
3694 * Parse image options text and use it to make an image
3696 function makeImage( &$nt, $options ) {
3697 global $wgContLang, $wgUseImageResize, $wgUser;
3701 # Check if the options text is of the form "options|alt text"
3703 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3704 # * left no resizing, just left align. label is used for alt= only
3705 # * right same, but right aligned
3706 # * none same, but not aligned
3707 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3708 # * center center the image
3709 # * framed Keep original image size, no magnify-button.
3711 $part = explode( '|', $options);
3713 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3714 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3715 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3716 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3717 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3718 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3719 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3720 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3723 $width = $height = $framed = $thumb = false;
3724 $manual_thumb = '' ;
3726 foreach( $part as $key => $val ) {
3727 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3729 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3730 # use manually specified thumbnail
3732 $manual_thumb = $match;
3733 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3734 # remember to set an alignment, don't render immediately
3736 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3737 # remember to set an alignment, don't render immediately
3739 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3740 # remember to set an alignment, don't render immediately
3742 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3743 # remember to set an alignment, don't render immediately
3745 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3746 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3747 # $match is the image width in pixels
3748 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3749 $width = intval( $m[1] );
3750 $height = intval( $m[2] );
3752 $width = intval($match);
3754 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3760 # Strip bad stuff out of the alt text
3761 $alt = $this->replaceLinkHoldersText( $caption );
3762 $alt = Sanitizer
::stripAllTags( $alt );
3764 # Linker does the rest
3765 $sk =& $this->mOptions
->getSkin();
3766 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3770 * Set a flag in the output object indicating that the content is dynamic and
3771 * shouldn't be cached.
3773 function disableCache() {
3774 $this->mOutput
->mCacheTime
= -1;
3778 * Callback from the Sanitizer for expanding items found in HTML attribute
3779 * values, so they can be safely tested and escaped.
3780 * @param string $text
3781 * @param array $args
3785 function attributeStripCallback( &$text, $args ) {
3786 $text = $this->replaceVariables( $text, $args );
3787 $text = $this->unstripForHTML( $text );
3791 function unstripForHTML( $text ) {
3792 $text = $this->unstrip( $text, $this->mStripState
);
3793 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3801 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3802 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3803 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3809 function getTags() { return array_keys( $this->mTagHooks
); }
3815 * @package MediaWiki
3819 var $mText, # The output text
3820 $mLanguageLinks, # List of the full text of language links, in the order they appear
3821 $mCategories, # Map of category names to sort keys
3822 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3823 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3824 $mVersion, # Compatibility check
3825 $mTitleText, # title text of the chosen language variant
3826 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3827 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3828 $mImages, # DB keys of the images used, in the array key only
3829 $mExternalLinks; # External link URLs, in the key only
3831 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3832 $containsOldMagic = false, $titletext = '' )
3834 $this->mText
= $text;
3835 $this->mLanguageLinks
= $languageLinks;
3836 $this->mCategories
= $categoryLinks;
3837 $this->mContainsOldMagic
= $containsOldMagic;
3838 $this->mCacheTime
= '';
3839 $this->mVersion
= MW_PARSER_VERSION
;
3840 $this->mTitleText
= $titletext;
3841 $this->mLinks
= array();
3842 $this->mTemplates
= array();
3843 $this->mImages
= array();
3844 $this->mExternalLinks
= array();
3847 function getText() { return $this->mText
; }
3848 function getLanguageLinks() { return $this->mLanguageLinks
; }
3849 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3850 function &getCategories() { return $this->mCategories
; }
3851 function getCacheTime() { return $this->mCacheTime
; }
3852 function getTitleText() { return $this->mTitleText
; }
3853 function &getLinks() { return $this->mLinks
; }
3854 function &getTemplates() { return $this->mTemplates
; }
3855 function &getImages() { return $this->mImages
; }
3856 function &getExternalLinks() { return $this->mExternalLinks
; }
3858 function containsOldMagic() { return $this->mContainsOldMagic
; }
3859 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3860 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3861 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3862 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3863 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3864 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3866 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3867 function addImage( $name ) { $this->mImages
[$name] = 1; }
3868 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3869 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3871 function addLink( $title, $id ) {
3872 $ns = $title->getNamespace();
3873 $dbk = $title->getDBkey();
3874 if ( !isset( $this->mLinks
[$ns] ) ) {
3875 $this->mLinks
[$ns] = array();
3877 $this->mLinks
[$ns][$dbk] = $id;
3880 function addTemplate( $title, $id ) {
3881 $ns = $title->getNamespace();
3882 $dbk = $title->getDBkey();
3883 if ( !isset( $this->mTemplates
[$ns] ) ) {
3884 $this->mTemplates
[$ns] = array();
3886 $this->mTemplates
[$ns][$dbk] = $id;
3893 function merge( $other ) {
3894 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3895 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3896 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3900 * Return true if this cached output object predates the global or
3901 * per-article cache invalidation timestamps, or if it comes from
3902 * an incompatible older version.
3904 * @param string $touched the affected article's last touched timestamp
3908 function expired( $touched ) {
3909 global $wgCacheEpoch;
3910 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3911 $this->getCacheTime() < $touched ||
3912 $this->getCacheTime() <= $wgCacheEpoch ||
3913 !isset( $this->mVersion
) ||
3914 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3919 * Set options of the Parser
3921 * @package MediaWiki
3925 # All variables are private
3926 var $mUseTeX; # Use texvc to expand <math> tags
3927 var $mUseDynamicDates; # Use DateFormatter to format dates
3928 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3929 var $mAllowExternalImages; # Allow external images inline
3930 var $mAllowExternalImagesFrom; # If not, any exception?
3931 var $mSkin; # Reference to the preferred skin
3932 var $mDateFormat; # Date format index
3933 var $mEditSection; # Create "edit section" links
3934 var $mNumberHeadings; # Automatically number headings
3935 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3936 var $mTidy; # Ask for tidy cleanup
3938 function getUseTeX() { return $this->mUseTeX
; }
3939 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3940 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3941 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3942 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3943 function &getSkin() { return $this->mSkin
; }
3944 function getDateFormat() { return $this->mDateFormat
; }
3945 function getEditSection() { return $this->mEditSection
; }
3946 function getNumberHeadings() { return $this->mNumberHeadings
; }
3947 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3948 function getTidy() { return $this->mTidy
; }
3950 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3951 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3952 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3953 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3954 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3955 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3956 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3957 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3958 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3959 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3960 function setSkin( &$x ) { $this->mSkin
=& $x; }
3962 function ParserOptions() {
3964 $this->initialiseFromUser( $wgUser );
3968 * Get parser options
3971 function newFromUser( &$user ) {
3972 $popts = new ParserOptions
;
3973 $popts->initialiseFromUser( $user );
3977 /** Get user options */
3978 function initialiseFromUser( &$userInput ) {
3979 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3980 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3981 $fname = 'ParserOptions::initialiseFromUser';
3982 wfProfileIn( $fname );
3983 if ( !$userInput ) {
3985 $user->setLoaded( true );
3987 $user =& $userInput;
3990 $this->mUseTeX
= $wgUseTeX;
3991 $this->mUseDynamicDates
= $wgUseDynamicDates;
3992 $this->mInterwikiMagic
= $wgInterwikiMagic;
3993 $this->mAllowExternalImages
= $wgAllowExternalImages;
3994 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3995 wfProfileIn( $fname.'-skin' );
3996 $this->mSkin
=& $user->getSkin();
3997 wfProfileOut( $fname.'-skin' );
3998 $this->mDateFormat
= $user->getOption( 'date' );
3999 $this->mEditSection
= true;
4000 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4001 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4002 $this->mTidy
= false;
4003 wfProfileOut( $fname );
4008 * Callback function used by Parser::replaceLinkHolders()
4009 * to substitute link placeholders.
4011 function &wfOutputReplaceMatches( $matches ) {
4012 global $wgOutputReplace;
4013 return $wgOutputReplace[$matches[1]];
4017 * Return the total number of articles
4019 function wfNumberOfArticles() {
4020 global $wgNumberOfArticles;
4023 return $wgNumberOfArticles;
4027 * Return the number of files
4029 function wfNumberOfFiles() {
4030 $fname = 'Parser::wfNumberOfFiles';
4032 wfProfileIn( $fname );
4033 $dbr =& wfGetDB( DB_SLAVE
);
4034 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4035 wfProfileOut( $fname );
4041 * Get various statistics from the database
4044 function wfLoadSiteStats() {
4045 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4046 $fname = 'wfLoadSiteStats';
4048 if ( -1 != $wgNumberOfArticles ) return;
4049 $dbr =& wfGetDB( DB_SLAVE
);
4050 $s = $dbr->selectRow( 'site_stats',
4051 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4052 array( 'ss_row_id' => 1 ), $fname
4055 if ( $s === false ) {
4058 $wgTotalViews = $s->ss_total_views
;
4059 $wgTotalEdits = $s->ss_total_edits
;
4060 $wgNumberOfArticles = $s->ss_good_articles
;
4066 * Basically replacing " > and < with HTML entities ( ", >, <)
4068 * @param string $in Text that might contain HTML tags
4069 * @return string Escaped string
4071 function wfEscapeHTMLTagsOnly( $in ) {
4073 array( '"', '>', '<' ),
4074 array( '"', '>', '<' ),